import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import javax.xml.parsers.ParserConfigurationException;
import javax.xml.xpath.XPathExpressionException;

import org.wggds.webservices.io.IWggdsResultUtil;
import org.wggds.webservices.io.UnknownWggdsQuerySubClass;
import org.wggds.webservices.io.WggdsQueryExcpetion;
import org.wggds.webservices.io.WggdsQueryInputUtil;
import org.wggds.webservices.io.WggdsQueryOutputUtil;
import org.wggds.webservices.io.WggdsResultException;
import org.wggds.webservices.io.WggdsResultUtilXml;
import org.wggds.webservices.io.data.BiologicalContext;
import org.wggds.webservices.io.data.CompleteInformation;
import org.wggds.webservices.io.data.CompositionComponent;
import org.wggds.webservices.io.data.ErrorId;
import org.wggds.webservices.io.data.ListOperation;
import org.wggds.webservices.io.data.OutputFormat;
import org.wggds.webservices.io.data.Persubstitution;
import org.wggds.webservices.io.data.QueryResult;
import org.wggds.webservices.io.data.WggdsError;
import org.wggds.webservices.io.query.CompositionSearchQuery;
import org.wggds.webservices.io.query.IdListQuery;
import org.wggds.webservices.io.query.ListOperationQuery;
import org.wggds.webservices.io.query.MassSearchQuery;
import org.wggds.webservices.io.query.SubstructureQuery;
import org.xml.sax.SAXException;

public class TestIO
{

    public static void main(String[] args) throws WggdsQueryExcpetion, WggdsResultException, IOException
    {
//    	TestIO.mass();
//    	TestIO.substructure();
//    	TestIO.composition();
//    	TestIO.listOperation();
//    	TestIO.idList();
//    	TestIO.writeResults();
    	
    	TestIO.testCFG();
    }

    private static void testCFG() throws IOException{
    	SubstructureQuery t_query = new SubstructureQuery();
        t_query.setFormat(OutputFormat.XML);
        t_query.setCompleteInformation(CompleteInformation.Complete);
        t_query.setExactMatch(false);
        t_query.setIgnoreReducingAlditol(true);
        t_query.setOtherResidues(false);
        t_query.setReducingEnd(false);
        t_query.setTerminal(false);
        
        String line;
        StringBuffer buf=new StringBuffer();
        BufferedReader reader=new BufferedReader(new FileReader(new File(TestIO.class.getResource("core.glydeII").getFile())));
        while((line=reader.readLine())!=null){
        	buf.append(line+"\n");
        }
        String t_sequence=buf.toString();
        
//        String t_sequence = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>"
//            + "\n<GlydeII>"
//            + "\n  <molecule subtype=\"glycan\" id=\"From_GlycoCT_Translation\">"
//            + "\n    <residue subtype=\"base_type\" partid=\"1\" ref=\"http://www.monosaccharideDB.org/GLYDE-II.jsp?G=a-dgal-HEX-1:5\" />"
//            + "\n    <residue subtype=\"substituent\" partid=\"2\" ref=\"http://www.monosaccharideDB.org/GLYDE-II.jsp?G=n-acetyl\" />"
//            + "\n    <residue subtype=\"base_type\" partid=\"3\" ref=\"http://www.monosaccharideDB.org/GLYDE-II.jsp?G=b-dgal-HEX-1:5\" />"
//            + "\n    <residue_link from=\"2\" to=\"1\">"
//            + "\n      <atom_link from=\"N1H\" to=\"C2\" to_replace=\"O2\" bond_order=\"1\" />"
//            + "\n    </residue_link>"
//            + "\n    <residue_link from=\"3\" to=\"1\">"
//            + "\n      <atom_link from=\"C1\" to=\"O3\" from_replace=\"O1\" bond_order=\"1\" />"
//            + "\n    </residue_link>"
//            + "\n  </molecule>"
//            + "\n</GlydeII>";
        t_query.setSequence(t_sequence);
        
        try {
        	//http://glycan-dev.mit.edu/glycomics/ws/carb/
			List<QueryResult>results=t_query.runQuery("http://localhost:8080/Wggds-IGG/Temp/");
			for(QueryResult result:results){
				System.err.println(result.getSequence());
			}
		} catch (WggdsQueryExcpetion e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (UnknownWggdsQuerySubClass e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
        
    }
    
    private static void writeResults() throws WggdsResultException, WggdsQueryExcpetion
    {
        IWggdsResultUtil t_util = new WggdsResultUtilXml("glycomedb", "http://www.glycome-db.org");
        t_util.startRecordResult("listId1");
        // create a complete query result
        QueryResult t_result = new QueryResult();
        t_result.setId("id1");
        String t_sequence = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>"
            + "\n<GlydeII>"
            + "\n  <molecule subtype=\"glycan\" id=\"From_GlycoCT_Translation\">"
            + "\n    <residue subtype=\"base_type\" partid=\"1\" ref=\"http://www.monosaccharideDB.org/GLYDE-II.jsp?G=a-dgal-HEX-1:5\" />"
            + "\n    <residue subtype=\"substituent\" partid=\"2\" ref=\"http://www.monosaccharideDB.org/GLYDE-II.jsp?G=n-acetyl\" />"
            + "\n    <residue_link from=\"2\" to=\"1\">"
            + "\n      <atom_link from=\"N1H\" to=\"C2\" to_replace=\"O2\" bond_order=\"1\" />"
            + "\n    </residue_link>"
            + "\n  </molecule>"
            + "\n</GlydeII>";
        t_result.setSequence(t_sequence);
        t_result.setUrl("http://www.glycome-db.org/database/showstructure.action?structureId=id1");
        // create a biological context
        List<BiologicalContext> t_list = new ArrayList<BiologicalContext>();
        BiologicalContext t_context = new BiologicalContext();
        t_context.setNcbiTaxonomyId("9606");
        t_context.setTaxonomyName("Homo sapiens");
        t_context.setTissueMeshId("abcde");
        t_context.setTissueName("Liver");
        t_list.add(t_context);
        t_result.setBiologicalSource(t_list);
        t_util.addResult(t_result, true);
        t_util.addResult(t_result, false);
        // any erros and warnings have to added after the results
        WggdsError t_error = new WggdsError();
        t_error.setId(ErrorId.DatabaseNotAvailable);
        t_error.setMessage("Database down");
        t_util.addError(t_error);
        // finish result and print it
        
        String resultXml=t_util.finishRecordResult();
        
        System.out.println(resultXml);
        
        List<QueryResult> result=WggdsQueryOutputUtil.parseQueryResult(resultXml);
		System.err.println(result.get(0).getSequence());
    }

    private static void composition() throws WggdsQueryExcpetion
    {
        CompositionSearchQuery t_query = new CompositionSearchQuery();
        t_query.setFormat(OutputFormat.XML);
        t_query.setAllowOtherResidues(true);
        t_query.setCompleteInformation(CompleteInformation.None);
        List<CompositionComponent> t_list = new ArrayList<CompositionComponent>();
        CompositionComponent t_component = new CompositionComponent();
        t_component.setMaxValue(10);
        t_component.setMinValue(10);
        String t_sequence = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>"
            + "\n<GlydeII>"
            + "\n  <molecule subtype=\"glycan\" id=\"From_GlycoCT_Translation\">"
            + "\n    <residue subtype=\"base_type\" partid=\"1\" ref=\"http://www.monosaccharideDB.org/GLYDE-II.jsp?G=a-dgal-HEX-1:5\" />"
            + "\n    <residue subtype=\"substituent\" partid=\"2\" ref=\"http://www.monosaccharideDB.org/GLYDE-II.jsp?G=n-acetyl\" />"
            + "\n    <residue_link from=\"2\" to=\"1\">"
            + "\n      <atom_link from=\"N1H\" to=\"C2\" to_replace=\"O2\" bond_order=\"1\" />"
            + "\n    </residue_link>"
            + "\n  </molecule>"
            + "\n</GlydeII>";
        t_component.setResidue(t_sequence);
        t_list.add(t_component);
        t_component = new CompositionComponent();
        t_component.setMaxValue(10);
        t_component.setMinValue(10);
        t_sequence = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>"
            + "\n<GlydeII>"
            + "\n  <molecule subtype=\"glycan\" id=\"From_GlycoCT_Translation\">"
            + "\n    <residue subtype=\"base_type\" partid=\"3\" ref=\"http://www.monosaccharideDB.org/GLYDE-II.jsp?G=b-dgal-HEX-1:5\" />"
            + "\n  </molecule>"
            + "\n</GlydeII>";
        t_component.setResidue(t_sequence);
        t_list.add(t_component);
        t_query.setComponents(t_list);
        
        // serialize to XML
        String t_xml = WggdsQueryOutputUtil.writeCompositionSearchQuery(t_query);
        System.out.println(t_xml);
        
        // parse the xml
        t_query = WggdsQueryInputUtil.parseCompositionSearchQuery(t_xml);
    }

    private static void substructure() throws WggdsQueryExcpetion
    {
        SubstructureQuery t_query = new SubstructureQuery();
        t_query.setFormat(OutputFormat.XML);
        t_query.setCompleteInformation(CompleteInformation.Complete);
        t_query.setExactMatch(false);
        t_query.setIgnoreReducingAlditol(true);
        t_query.setOtherResidues(false);
        t_query.setReducingEnd(false);
        t_query.setTerminal(false);
        String t_sequence = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>"
            + "\n<GlydeII>"
            + "\n  <molecule subtype=\"glycan\" id=\"From_GlycoCT_Translation\">"
            + "\n    <residue subtype=\"base_type\" partid=\"1\" ref=\"http://www.monosaccharideDB.org/GLYDE-II.jsp?G=a-dgal-HEX-1:5\" />"
            + "\n    <residue subtype=\"substituent\" partid=\"2\" ref=\"http://www.monosaccharideDB.org/GLYDE-II.jsp?G=n-acetyl\" />"
            + "\n    <residue subtype=\"base_type\" partid=\"3\" ref=\"http://www.monosaccharideDB.org/GLYDE-II.jsp?G=b-dgal-HEX-1:5\" />"
            + "\n    <residue_link from=\"2\" to=\"1\">"
            + "\n      <atom_link from=\"N1H\" to=\"C2\" to_replace=\"O2\" bond_order=\"1\" />"
            + "\n    </residue_link>"
            + "\n    <residue_link from=\"3\" to=\"1\">"
            + "\n      <atom_link from=\"C1\" to=\"O3\" from_replace=\"O1\" bond_order=\"1\" />"
            + "\n    </residue_link>"
            + "\n  </molecule>"
            + "\n</GlydeII>";
        t_query.setSequence(t_sequence);
        
        // serialize to XML
        String t_xml = WggdsQueryOutputUtil.writeSubstructureQuery(t_query);
        System.out.println(t_xml);
        
        // parse the xml
        t_query = WggdsQueryInputUtil.parseSubstructureQuery(t_xml);
    }

    private static void idList() throws WggdsQueryExcpetion
    {
        // create the query
        IdListQuery t_query = new IdListQuery();
        t_query.setFormat(OutputFormat.JSON);
        t_query.setGlydeVersion("1.1");
        t_query.setNamespace("cfg");
        List<String> t_idlist = new ArrayList<String>();
        t_idlist.add("34");
        t_idlist.add("340");
        t_idlist.add("341");
        t_query.setIdList(t_idlist);
        
        // serialize to XML
        String t_xml = WggdsQueryOutputUtil.writeIdListQuery(t_query);
        System.out.println(t_xml);
        
        // parse the xml
        t_query = WggdsQueryInputUtil.parseIdListQuery(t_xml);
    }

    private static void listOperation() throws WggdsQueryExcpetion
    {
        // create the query
        ListOperationQuery t_query = new ListOperationQuery();
        t_query.setCompleteInformation(CompleteInformation.ID);
        t_query.setFormat(OutputFormat.JSON);
        t_query.setListOne("list255");
        t_query.setListTwo("list437645");
        t_query.setOperation(ListOperation.AND);
        
        // serialize to XML
        String t_xml = WggdsQueryOutputUtil.writeListOperationQuery(t_query);
        System.out.println(t_xml);
        
        // parse the xml
        t_query = WggdsQueryInputUtil.parseListOperationQuery(t_xml);
    }

    private static void mass() throws WggdsQueryExcpetion
    {
        // create the query
        MassSearchQuery t_query = new MassSearchQuery();
        t_query.setCompleteInformation(CompleteInformation.ID);
        t_query.setFormat(OutputFormat.XML);
        t_query.setInterval(400D);
        t_query.setMass(1987.7D);
        t_query.setMonoisotopic(true);
        t_query.setPersubstitution(Persubstitution.None);
        
        // serialize to XML
        String t_xml = WggdsQueryOutputUtil.writeMassSearchQuery(t_query);
        System.out.println(t_xml);
        
        // parse the xml
        t_query = WggdsQueryInputUtil.parseMassSearchQuery(t_xml);
    }

}
